package com.wxx.controller.upload;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.wxx.common.Const;
import com.wxx.service.tool.oss.OssService;
import com.wxx.service.tool.qiniu.QiNiuService;
import com.wxx.util.AppUtil;
import com.wxx.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/uploadFiles")
@Scope("prototype")
public class UploadController {

    Map<String,Object> map = null;

    @Resource
    private QiNiuService qiNiuService;
    @Resource
    private OssService ossService;

    /**
     * 百度编辑器所有上传功能（使用所有上传）
     *
     * @param request
     * @param file
     * @param type  1.本地 2.oss
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFileByUEditor",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFileByUEditor(HttpServletRequest request, @RequestParam MultipartFile file, Integer type) throws IOException {
        ApplicationHome h = new ApplicationHome(this.getClass());
        // D:\idea\springboot2.x\target
        String parent = h.getSource().getParent();
        File path1 = h.getDir();


        Map map = Maps.newHashMap();
        String url = "";
        switch (type){
            case 1:
                //上传到本地
                url = saveImg(file, request);
                if (StringUtils.isNotBlank(url)) {
                    map.put("state", "SUCCESS");
                    //绝对路径，百度编辑器的前缀无需配置
                    map.put("url", PropertiesUtil.getProperty("URL") + url);
                }else{
                    map.put("state", "ERROR");
                }
                break;
            case 2:
                //上传到OSS
                Map upload = ossService.upload(file);
                if (StringUtils.equals(Const.SUCCESS_CODE_STR,upload.get("code").toString())){
                    url = (String) upload.get("url");
                    map.put("state", "SUCCESS");
                    //绝对路径，百度编辑器的前缀无需配置
                    map.put("url", PropertiesUtil.getProperty("URL") + url);
                }
                break;
            default:
                break;
        }
        return map;
    }

    /**
     * 批量上传多个文件到 OSS
     * 传递相对路径 逗号拼接的文件地址
     *
     * @param files
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFilesBatchToOSS",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFilesBatchToOSS(@RequestParam MultipartFile[] files) throws IOException {
        map = Maps.newHashMap();
        Map map = ossService.uploadBatch(files);
        return map;
    }

    /**
     * 上传单个文件到 OSS （所有文件均可上传）
     * 注：如果上传的是视频会自动转码成 MP4格式
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFileToOSS",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFileToOSS(@RequestParam MultipartFile file) throws IOException {
        map = Maps.newHashMap();
        Map map = ossService.upload(file);
        return map;
    }


    /**
     * wangEdit上传单张或多张图片方法
     * @param files
     * @param request
     * @return
     */
    @RequestMapping(value = "/wangEditUploadImag",method = RequestMethod.POST)
    @ResponseBody
    public Object wangEditUploadImag(@RequestParam List<MultipartFile> files, HttpServletRequest request){
        map=new HashMap<>();
        String[] imgUrls = new String[files.size()];
        try {
            if(files != null&&files.size()>0) {
                for (int i = 0; i < files.size(); i++) {
                    MultipartFile file = files.get(i);
                    /*
                     * servcie保存file
                     * 这里根据自己的上传服务器方法来实现
                     */
//                    String url = saveImg(file,request);
                    /**
                     * 上传七牛云
                     */
                    String url = saveImgToQiNiu(file);
                    if (!"".equals(url)){
                        imgUrls[i] = url;
                    }
                }
            }

            //成功的话
            map.put("errno",0);
            map.put("data", imgUrls);
        } catch (Exception e) {
            map.put("errno","500");
            map.put("msg",e);
            e.printStackTrace();
        }
        return JSONObject.toJSON(map);
    }

    /**
     * layui 上传单张图片 MultipartFile file 获取文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadOnlyImage",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadOnlyImage(@RequestParam MultipartFile file, HttpServletRequest request){
        map=new HashMap<>();
        try {
//            /**
//             * 调用保存图片的方法
//             */
//            String url = saveImg(file,request);
//            /**
//             * 上传七牛云
//             */
//            String url = saveImgToQiNiu(file);

            /**
             * 上传到oss
             */
            String url = saveImgToOss(file);

            if (!"".equals(url)){
                map.put("code",200);
                map.put("data",url);
            }else{
                map.put("code",500);
                map.put("data",url);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.toJSON(map);
    }

    /**
     * layui 上传webuploader文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadOnlyFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadOnlyfile(@RequestParam MultipartFile file, HttpServletRequest request){
        map=new HashMap<>();
        String url="";
        try {
            /**
             * 调用保存图片的方法
             */
             url = saveImg(file,request);
//            /**
//             * 上传七牛云
//             */
//            String url = saveImgToQiNiu(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * layui 上传多张图片 MultipartFile[] file 获取文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadManyImage",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadManyImage(@RequestParam MultipartFile[] file, HttpServletRequest request){
        map=new HashMap<>();
        if (file.length>0) {
            List<String> urlList = new ArrayList<>();
            for (int i = 0; i < file.length; i++) {
                try {
                    /**
                     * 调用保存图片的方法
                     */
                    String url = saveImg(file[i], request);
//                    /**
//                     * 上传七牛云
//                     */
//                    String url = saveImgToQiNiu(file[i]);
                    if (!"".equals(url)) {
                        urlList.add(url);
                    } else {
                        map.put("code", 500);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            map.put("urlList",urlList);
            map.put("code",200);
        }
        return JSONObject.toJSON(map);
    }


    /**
     * 通用上传图片
     * 上传路径需要切换
     * @param myFileName
     * @param request
     * @return
     * @throws IOException
     */
    private String saveImg(MultipartFile myFileName, HttpServletRequest request) throws IOException {

        String realName = "";
        if (myFileName != null) {
            String fileName = myFileName.getOriginalFilename();
            String fileNameExtension = fileName.substring(fileName.indexOf("."));
            // 生成实际存储的真实文件名
            realName = AppUtil.uuid() + fileNameExtension;
            //  获取项目根目录下的upload文件夹
            ApplicationHome h = new ApplicationHome(this.getClass());
            // D:\idea\springboot2.x\target 获取根目录 upload 跟 项目jar平级
            String path = h.getSource().getParent();
            String realPath = path + "/upload/";
            //判断文件夹是否存在，不存在就创建
            File filePath = new File(realPath);
            if (!filePath.exists()) {
                filePath.mkdir();
            }
            File uploadFile = new File(realPath, realName);
            myFileName.transferTo(uploadFile);
        }else{
            return "";
        }
        //本地相对图片地址
        String str = "upload/"+realName;
        return str;
    }

    /**
     * wangEdit上传图片到七牛云
     * @param myFileName
     * @return
     * @throws IOException
     */
    private String saveImgToQiNiu(MultipartFile myFileName) throws IOException {
        String str="";
        Map map = qiNiuService.uploadPhoto(myFileName);
        if ("200".equals(map.get("code").toString())){
//          存相对路径
            str=map.get("key").toString();
            System.out.println(str);
            return str;
        }else {
            return str;
        }
    }

    /**
     * @param myFileName
     * @return
     * @throws IOException
     */
    private String saveImgToOss(MultipartFile myFileName) throws IOException {
        String str="";
        Map map = ossService.upload(myFileName);
        if ("200".equals(map.get("code").toString())){
//          存相对路径
            str=map.get("url").toString();
            System.out.println(str);
            return str;
        }else {
            return str;
        }
    }




}
